﻿using Furion.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text;
using System;
using System.Threading.Tasks;
using BJYJ_Admin.Application.System.Services;

namespace BJYJ_Admin.Web.Core;

public class BasicAuthenticationDefaults
{
    public const string AuthenticationScheme = "BasicAuthentication";
}

public class JwtHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    private readonly UserService _userService;

    public JwtHandler(IOptionsMonitor<AuthenticationSchemeOptions> options
        , ILoggerFactory logger
        , UrlEncoder encoder
        , UserService userService)   // 依赖注入你的用户服务或者用户表仓储
        : base(options, logger, encoder)
    {
        _userService = userService;
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // 检查请求报文头是否包含 Authorization 头，且值以 （Basic ）开头
        if (!Context.Request.Headers.TryGetValue("Authorization", out StringValues authorizationHeader)
            || !authorizationHeader.ToString().StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
        {
            return AuthenticateResult.NoResult();
        }

        // 读取请求报文头 Authorization 的信息并进行 Base64 解码
        var token = authorizationHeader.ToString()[6..].Trim();
        var credentialString = Encoding.UTF8.GetString(Convert.FromBase64String(token));

        // 通过 : 分隔符分割出用户名和密码
        var credentials = credentialString.Split(':');
        string username = credentials[0];
        string password = credentials[1];

        // ========================== 验证你的用户名密码（成功）==========================
        if ( _userService.ValidateCredentials(username, password))
        {
            // 验证成功写入授权上下文票据
            var claims = new[] { new Claim(ClaimTypes.NameIdentifier, username) };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, null, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }

        // 验证失败返回
        return AuthenticateResult.Fail("Invalid username or password.");
    }
}

//namespace BJYJ_Admin.Web.Core;

//public class JwtHandler : AppAuthorizeHandler
//{
//    public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
//    {
//        // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false

//        return Task.FromResult(true);
//    }
//}